package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestAddUserEvent;
import com.android.kmlmrg.listener.custom.RestAddUserListener;
import com.android.kmlmrg.listener.custom.UsersListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;


/**
 * 
 * @author mayki
 *
 */
public class AddUser  extends AsyncTask<Void, Void, String> {



	/**LOG**/
	private static final  String LOG_TAG = AddUser.class.getSimpleName();

	private static final String METHODE_NAME = "/addUser";

	private static final String JSON_FIELD_IDENTIFICATION = "identifiant";

	private static final String JSON_FIELD_STATUS = "status";
	
	private static  ArrayList<RestAddUserListener> listeners = new ArrayList<RestAddUserListener>();

	private User user;
	
	private Application application;
	
	private Activity activity;
	
	private int code;

	public AddUser(Application pApplication, User pUser) {
		application =pApplication;
		Log.i(LOG_TAG, "START - Constructeur AddUser (Application pApplication, User pUser) ");
		user = pUser;	
		Log.i(LOG_TAG, "END - Constructeur AddUser ");
	}
	
//	public AddUser(Activity pActivity, User pUser) {
//
//		Log.i(LOG_TAG, "START - Constructeur AddUser (Application pApplication, User pUser) ");
//		application =pActivity.getApplication();;
//		activity = pActivity;
//		user = pUser;		
//		Log.i(LOG_TAG, "END - Constructeur AddUser ");
//	}	
	
	@Override
	protected String doInBackground(Void... params) {
		Log.i(LOG_TAG, "START - doInBackground ");
		try {
			String vUrl = application.getString(R.string.user_endpoint) + METHODE_NAME ;

			ApiSession vApiSession =  ServiceController.getInstance().getApiSession() ;
			JSONObject vJsonObject = new JSONObject();				
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId());
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH, vApiSession.getHash());
			String message = user.toData();

		
			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));

			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");

			httpcon.setDoInput(true);
			httpcon.setDoOutput(true);
			httpcon.setFixedLengthStreamingMode(message.getBytes().length);
			httpcon.connect();


			OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
			os.write(message.getBytes());
			//clean up
			os.flush();


			// this will be useful so that you can show a typical 0-100% progress bar
			int fileLength = httpcon.getContentLength();
			
			 code = httpcon.getResponseCode();


			InputStream input = httpcon.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(input));
			StringBuilder total = new StringBuilder();
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			os.flush();
			os.close();
			input.close();	
			Log.i(LOG_TAG, "START - doInBackground ");
			return total.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i(LOG_TAG, "START -  onPostExecute(int pStatusCode, String in)");
		Log.i(LOG_TAG, "result : " + result);
		RestAddUserEvent vUserAddEvent = new RestAddUserEvent(this, "", false);
		try {			
			if (code == HttpStatus.SC_OK) {
				JSONObject vJsonObject = new JSONObject(result);
				String vStatus;
				vStatus = (String) vJsonObject.get(JSON_FIELD_STATUS);
		
				if (vStatus != null && vStatus.equalsIgnoreCase("true")) {
					String vIdentification = (String) vJsonObject.get(JSON_FIELD_IDENTIFICATION);
					Log.i(LOG_TAG, "indentifiant : " + result);
					 vUserAddEvent = new RestAddUserEvent(this, vIdentification, true);
				} else if (vStatus!= null && vStatus.equalsIgnoreCase("false")) {

				}			
				
			} else if (code == HttpStatus.SC_REQUEST_TIMEOUT ) {

			} else {

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		fireAddUser(vUserAddEvent);
		Log.i(LOG_TAG, "END - onPostExecute( String in )");
	}

	


	
	

	@Override
	protected void onCancelled() {
		Log.i(LOG_TAG, "START - onCancelled ");
		Log.i(LOG_TAG, "END - onCancelled ");
	}

	@Override
	protected void onCancelled(String result) {
		Log.i(LOG_TAG, "START - onCancelled ");
		Log.i(LOG_TAG, "END - onCancelled ");
		super.onCancelled(result);
	}

	@Override
	protected void onPreExecute() {
		Log.i(LOG_TAG, "START - onPreExecute ");
		Log.i(LOG_TAG, "END - onPreExecute ");
		super.onPreExecute();
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		Log.i(LOG_TAG, "START - onProgressUpdate ");
		Log.i(LOG_TAG, "END - onProgressUpdate ");
		super.onProgressUpdate(values);
	}

	public static void addListener ( RestAddUserListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( UsersListener pListener ){
		listeners.remove(pListener);
	}

	public static void fireAddUser( RestAddUserEvent pUserAddEvent ){		
		for(RestAddUserListener listener : listeners){
			listener.resultAddUserRequest( pUserAddEvent );
		}
	}




}
